package com.hebeiwangxiaozhang.product.service;

import com.hebeiwangxiaozhang.pojo.CommodityEsBody;
import com.hebeiwangxiaozhang.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ProductService {

    Logger logger= LoggerFactory.getLogger(ProductService.class);

    @Autowired
    private RestHighLevelClient highLevelClient;

    public List<String> onSaleToEs(List<CommodityEsBody> esBodies) {
        BulkRequest request = new BulkRequest();
        esBodies.forEach(body ->
            request.add(new IndexRequest().index("commodity").
                    id(body.getSkuId().toString()) //这样做的好处是，如果ES已经存在这个sku数据，则进行更新，不存在就新增，避免重复上架
                    .source(JsonUtils.toJSONString(body), XContentType.JSON)
            )
        );
        BulkResponse bulk = null;
        try {
            bulk = highLevelClient.bulk(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            logger.info("bulkrequest for product on-sale has exceptions, details error = {}", e);
        }
        List<String> failedBulkList = new ArrayList<>();
        if (bulk.hasFailures()) {
            for (BulkItemResponse res : bulk.getItems()) {
                if(res.isFailed()) {
                    failedBulkList.add(res.getId());
                }
            }
        }
        return failedBulkList;
    }
}
